<!--
 * @Author: zhangfeng
 * @Date: 2024-01-17 17:28:38
 * @LastEditTime: 2024-02-01 17:54:32
 * @LastEditors: zhangfeng
 * @Description: 
 * @FilePath: \manager\managersystem\src\components\Upload\Upload.vue
 * © 2023 张峰，All rights reserved.
-->
<template>
	<el-upload
		class="avatar-uploader"
		:action="actions"
		:show-file-list="false"
		:on-success="handleAvatarSuccess"
		:before-upload="beforeAvatarUpload"
		:auto-upload="autoUpload"
	>
		<img v-if="imageUrl" :src="host + imageUrl" class="avatar" />
		<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
	</el-upload>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

import type { UploadProps } from 'element-plus';

const host = import.meta.env.VITE_API_PREFIX;

const props = defineProps({
	autoUpload: {
		type: Boolean,
		default: true,
	},
	actions: {
		type: String,
		default: '',
	},
	modelValue: {
		type: String,
		default: '',
	},
});

onUpdated(() => {
	imageUrl.value = props.modelValue;
});
const imageUrl = ref(props.modelValue);
const emit = defineEmits(['update:modelValue']);
// valueHtml 值发生变化时 触发emit事件 并将值赋值给vmodle

const handleAvatarSuccess: UploadProps['onSuccess'] = (
	response,
	uploadFile
) => {
	imageUrl.value = response.result.article_url;
	emit('update:modelValue', imageUrl.value);
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
	if (rawFile.type !== 'image/jpeg') {
		ElMessage.error('Avatar picture must be JPG format!');
		return false;
	} else if (rawFile.size / 1024 / 1024 > 10) {
		ElMessage.error('Avatar picture size can not exceed 10MB!');
		return false;
	}
	return true;
};
</script>

<style scoped>
.avatar-uploader .avatar {
	width: 178px;
	height: 178px;
	display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
	border: 1px dashed var(--el-border-color);
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
	border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	text-align: center;
}
</style>
